package edu.zut.controller;

import edu.zut.dao.UserDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设定编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //获取表单数据,如果表单不输入数据，返回null
        String account = request.getParameter("account");
        String psw = request.getParameter("psw");
        System.out.println("account = " + account);
        System.out.println("psw = " + psw);
        String error;
        //账号、密码的非空校验，如果为空，返回登录页面，并告知用户用户名或者密码不能为空
        if (null == account || account.trim().length() == 0 || null == psw || psw.trim().length() == 0) {
            error = "用户名或者密码不能为空";
            //资源的跳转：重定向  转发
            //重定向：可以根据指定的url进行资源的跳转   /表示的是web容器的跟路劲   但是我们想再跳转url的同时携带信息？
//            response.sendRedirect(request.getContextPath() + "/html/login.html");
            //转发：根据url进行服务器内部资源的转发，此时可以共享信息（request、response）
            request.setAttribute("error", error);
            //创建一个分发器,转发到登录页面资源    /表示的是当前应用程序的路劲
            RequestDispatcher dispatcher = request.getRequestDispatcher("/loginPage");
            dispatcher.forward(request, response);
        } else {
            //校验账号密码是否正确
            UserDao userDao = new UserDao();
            boolean result = userDao.loginQuery(account, psw);
            if (result) {
                //返回true表示登陆成功，跳转到首页
                request.setAttribute("name",account);
                request.getRequestDispatcher("/indexPage").forward(request, response);
            } else {
                //返回false表示登录失败，重新返回登录页面，并告知用户账号或密码错误
                error = "账号或密码错误";
                request.setAttribute("error", error);
                request.getRequestDispatcher("/loginPage").forward(request, response);
            }

        }


    }
}
